﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Service.Tool
{
    /// <summary>
    /// ini帮助类
    /// </summary>
    public class IniHelper
    {
        /// <summary>
        /// 写操作
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

        /// <summary>
        /// 读操作
        /// </summary>
        /// <param name="section">节</param>
        /// <param name="key">键</param>
        /// <param name="defaultValue">未读取到的默认值</param>
        /// <param name="retValue">读取到的值</param>
        /// <param name="size">大小</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retValue, int size, string filePath);

        /// <summary>
        /// 读取Ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadIni(string section, string key, string defaultValue, string filename)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + filename;

            if (!File.Exists(filePath))
                return defaultValue;

            StringBuilder retValue = new StringBuilder();
            GetPrivateProfileString(section, key, defaultValue, retValue, 256, filePath);
            return retValue.ToString();
        }

        /// <summary>
        /// 写入Ini文件
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static long WriteIni(string section, string key, string value)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + @"\User.ini";
            return WritePrivateProfileString(section, key, value, filePath);
        }
    }
}
